package com.booter.producer.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.zaxxer.hikari.HikariDataSource;
/**
 * 数据源创建时不会初始化连接池，当getConnection后才会后连接池相关配置
 */
@Configuration
public class DsConfig {

	private static final Logger log = LoggerFactory.getLogger(DsConfig.class);


	@Bean
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource.ds")
	public DataSource ds() {
		return DataSourceBuilder.create().type(HikariDataSource.class).build();
	}

	@Bean(name = "sessionFactory")
	public SqlSessionFactory sqlSessionFactory(
			@Qualifier("ds") DataSource dataSource) {
		try {
			SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
			bean.setDataSource(dataSource);
			ResourcePatternResolver configResolver = new PathMatchingResourcePatternResolver();
			Resource rs =configResolver.getResource("classpath:mybatis/config/mybatis-config.xml");
			bean.setConfigLocation(rs);

			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource[] resources = resolver.getResources("classpath*:mybatis/mapper/*Mapper.xml");
			bean.setMapperLocations(resources);
			return bean.getObject();
		} catch (Exception ex) {
			log.error("",ex);
		}
		return null;
	}
	@Primary
	@Bean(name = "tx")
	public DataSourceTransactionManager transactionManager(
			@Qualifier("ds") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
	@Primary
	@Bean(name = "sessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(
			@Qualifier("sessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
